<?php
namespace MkGc\Controller;

use Think\Controller;
use Think\Model;

define("DATA_ATT_ROOT_PATH", "../DataAtt/NW");
define("DATA_TEMP_ROOT_PATH", "../DataTemp/NW");

define("JSXY_PACK_PATH", DATA_TEMP_ROOT_PATH . "/Pack");
define("NEWS_PATH", DATA_ATT_ROOT_PATH . "/News");
define("PIC_SUB_PATH", DATA_ATT_ROOT_PATH . "/Pic");
define("GCJF_SUB_PATH", DATA_ATT_ROOT_PATH . "/GcFile");
//define("PIC_SUB_PATH", "Pic");
//define("GCJF_SUB_PATH", "GcFile");

define("SPSTR_1", "sp1fsp1");
define("SPSTR_2", "sp2fsp2");
define("FILE_SPSTR_1", "spdotsp");

class GclbController extends Controller
{
    public function index()
    {
    }

    public function listData()
    {
        $gclb = M("Gclb");

        //过滤显示 -> 调试ts , 验收ys
        $filter_fl = I("post.filter_fl", "0");
        $condition = [];
        // if ($filter_fl == "ts")
        //     $condition["ts_sf"] = "是";
        // if ($filter_fl == "ys")
        //     $condition["ys_sf"] = "是";
        if ($filter_fl == "wts")
            $condition["ts_sf"] = ["neq", "是"];
        if ($filter_fl == "wys")
            $condition["ys_sf"] = ["neq", "是"];
        if ($filter_fl == "ts")
            $condition["ts_sf"] = ["eq", "是"];
        if ($filter_fl == "ys")
            $condition["ys_sf"] = ["eq", "是"];

        $total    = $gclb->where($condition)->getField("count(*) as rec_count");
        $list_ary = $gclb
            ->where($condition)
            ->page(strval(I("post.page", 1)) . "," . strval(I("post.rows", 100)))
            ->order("htjh_rq desc,gc_mc")
            ->select();

        // //合同金额显示控制
        // if (getLoginFlag() === false)
        // {
        //     foreach ($list_ary as $k => $v)
        //         $list_ary[$k]["ht_je"] = "*";
        // }

        $result_ary["total"] = $total;
        $result_ary["rows"]  = $list_ary;

        $this->ajaxReturn($result_ary);
    }

    private function modiData($modiFlag)
    {
        $rules         = array(
            array("gh_mc", "require", "客户名称 必须输入"),
            array("ht_je", "require", "合同金额 必须输入"),
            array("gq", "require", "工期（天） 必须输入"),

            array('yfk_rq', '/^\d{4}-\d{1,2}-\d{1,2}$/', '预付款日期 有误'),
            array('jh_rq', '/^\d{4}-\d{1,2}-\d{1,2}$/', '交货日期 有误'),
        );
        $data          = array_merge(I("post."));
        $data["ht_je"] = floatval($data["ht_je"]);

        $mdfData = D("Gclb");
        if (!$mdfData->validate($rules)->create($data))
        {
            $result_ary = array("error" => 1, "infoAry" => $mdfData->getError());
            $this->ajaxReturn($result_ary);
        }
        else
        {
            if ($modiFlag == 1)
            {
                $data["cr_data"] = date("Y-m-d"); //数据格式 2017-01-01
                $data["id"]      = $mdfData->field("id", true)->add($data);
            }
            if ($modiFlag == 2)
                $mdfData->where("id=" . strval($data["id"]))->save($data);

            $result_ary = array("error" => 0, "infoAry" => $data);
            $this->ajaxReturn($result_ary);
        }
    }

    public function addData()
    {
        $this->modiData(1);
    }

    public function updateData()
    {
        $this->modiData(2);
    }

    public function delData()
    {
        //删除扫描图片
        $mdfData = M("Gclb");
        $cr_data = $mdfData->where("id=" . I("post.id"))->getField("cr_data");
        // $directory = DATA_ATT_ROOT_PATH . "/" . PIC_SUB_PATH . "/" . explode("-", $cr_data)[0] . "/" . explode("-", $cr_data)[1] . "/";
        $directory = PIC_SUB_PATH . "/" . explode("-", $cr_data)[0] . "/" . explode("-", $cr_data)[1] . "/";

        $delFile = [];
        if (is_dir($directory) == true)
        {
            $mydir = dir($directory);
            while ($file = $mydir->read())
            {
                if ((is_dir($directory . "/" . $file)) AND ($file != ".") AND ($file != ".."))
                {
                }
                else if (($file != ".") AND ($file != ".."))
                {
                    $prefixPic = I("post.id") . "_";
                    if (substr($file, 0, strlen($prefixPic)) == $prefixPic)
                    {
                        array_push($delFile, $directory . "/" . $file);
                    }

                }
            }
            $mydir->close();
        }

        //实际删除图片
        foreach ($delFile as $k => $v)
            unlink($v);

        //删除进度款
        $mdfData = M("Gcjdk");
        $mdfData->where("pid=" . I("post.id"))->delete();

        //删除工程条目
        $mdfData = M("Gclb");
        $mdfData->where("id=" . I("post.id"))->delete();
    }

    public function getHtPic()
    {
        $fl      = I("post.fl");
        $gclb    = M("Gclb");
        $cr_data = $gclb->where("id=" . I("post.id"))->getField("cr_data");

        //遍历目录
        $ht_list  = [];
        $fp_list  = [];
        $fhd_list = [];
        // $directory = DATA_ATT_ROOT_PATH . "/" . PIC_SUB_PATH . "/" . explode("-", $cr_data)[0] . "/" . explode("-", $cr_data)[1];
        $directory = PIC_SUB_PATH . "/" . explode("-", $cr_data)[0] . "/" . explode("-", $cr_data)[1];

        if (is_dir($directory) == true)
        {
            $mydir = dir($directory);
            while ($file = $mydir->read())
            {
                if ((is_dir($directory . "/" . $file)) AND ($file != ".") AND ($file != ".."))
                {
                }
                else if (($file != ".") AND ($file != ".."))
                {
                    if (strpos($file, I("post.id") . "_" . $fl) !== false)
                        array_push($ht_list, $directory . "/" . $file);
                }
            }
            $mydir->close();
        }

        sort($ht_list);
        sort($fp_list);
        sort($fhd_list);
        $result_ary = array("cr_data" => $cr_data, "ht" => $ht_list, "fp" => $fp_list, "fhd" => $fhd_list);
        $this->ajaxReturn($result_ary);
    }

    public function getHtPicMaxIndex()
    {
        $gclb    = M("Gclb");
        $cr_data = $gclb->where("id=" . I("post.id"))->getField("cr_data");
        $fl      = I("fl");

        $subPath = PIC_SUB_PATH;
        //工程文件
        if (strtolower($fl) == "gcsj")
            $subPath = GCJF_SUB_PATH;

        // $directory = DATA_ATT_ROOT_PATH . "/" . $subPath . "/" . explode("-", $cr_data)[0] . "/" . explode("-", $cr_data)[1] . "/";
        $directory = $subPath . "/" . explode("-", $cr_data)[0] . "/" . explode("-", $cr_data)[1] . "/";

        $fileList = getFileList($directory);
        $maxIndex = 0;
        foreach ($fileList as $k => $v)
        {
            $file = basename($v);
            if (strpos($file, I("post.id") . "_" . strval($fl)) !== false)
            {
                $fileName = explode(".", $file)[0];
                $fileName = explode("_", $fileName)[2];
                if (intval($fileName) > $maxIndex)
                    $maxIndex = intval($fileName);

                array_push($fileList, $file);
                array_push($fileList, $fileName);
            }
        }

        $result_ary = array("maxPicIndex" => $maxIndex, "fileList" => $fileList);
        $this->ajaxReturn($result_ary);
    }

    public function delMFile()
    {
        $fileName = I("post.delFile");
        $fileName = iconv('utf-8', 'gbk', $fileName);
        if (file_exists($fileName))
            unlink($fileName);

        $result_ary = array("delFlag" => 1);
        $this->ajaxReturn($result_ary);
    }

    public function delHtAllPic()
    {
        $fileNameList = I("post.delFileList");
        foreach ($fileNameList as $k => $v)
        {
            if (file_exists($v))
                unlink($v);
        }

        $result_ary = array("delFlag" => $fileNameList);
        $this->ajaxReturn($result_ary);
    }

    public function getGcJc()
    {
        //车间生产情况,工程设计情况
        $gclb = M("Gclb");
        $data = $gclb->where("id=" . strval(I("post.id")))->find();

        $result_ary["data"] = $data;
        $this->ajaxReturn($result_ary);
    }

    public function updateGcJc()
    {
        //车间生产情况,工程设计情况
        $gclb      = M("Gclb");
        $fieldName = "";

        if (I("post.fl") == 1)
            $fieldName = "sj_qk";
        if (I("post.fl") == 2)
            $fieldName = "cg_qk";
        if (I("post.fl") == 3)
            $fieldName = "cj_qk";

        $data[$fieldName] = I("post.data");
        $gclb->where("id=" . strval(I("post.id")))->save($data);
    }

    public function updateFile()
    {
        if (strtolower(I("post.fl")) == "gcsj")
        {
            //工程文件
            $exts = null;
            // $rootPath = DATA_ATT_ROOT_PATH . "/" . GCJF_SUB_PATH . "/";
            $rootPath = GCJF_SUB_PATH . "/";
            $saveName = I("post.saveName");
            $fileName = I("post.fileName");

            $saveName =
                explode("_", $saveName)[0] . "_" .
                explode("_", $saveName)[1] . "_" .
                explode("_", $saveName)[2] . "_" . FILE_SPSTR_1 .
                iconv('utf-8', 'gbk', explode(".", $fileName)[0]);
        }
        else
        {
            $exts = array('jpg', 'gif', 'png', 'jpeg');
            // $rootPath = DATA_ATT_ROOT_PATH . "/" . PIC_SUB_PATH . "/";
            $rootPath = PIC_SUB_PATH . "/";
            $saveName = I("post.saveName");
        }
        if (is_dir($rootPath) == false)
            mkdir($rootPath, 0777, true);

        $upload           = new \Think\Upload();   // 实例化上传类
        $upload->replace  = true;
        $upload->maxSize  = 1000 * 1024 * 1024;    // 设置附件上传大小
        $upload->exts     = $exts;                 // 设置附件上传类型
        $upload->rootPath = $rootPath;             // 设置附件上传根目录 "./DataPic/", "./DataPic/Pic/"

        $upload->autoSub  = true;
        $upload->subName  = I("post.subName");     // 子目录 "2017/09";
        $upload->saveName = $saveName;             // 上传文件名 不包含文件扩展名(23_ht_00001)

        // 上传文件
        $info = $upload->upload();
        if (!$info)
        {
            // 上传错误提示错误信息
            $this->error($upload->getError());
        }
        else
        {
            // 上传成功
            $this->success('上传成功！');
        }
    }

    //--------------------------------------------------
    public function getListJdk()
    {
        $gclb = M("Gcjdk");

        $list_ary            = $gclb->page(strval(I("post.page", 1)) . "," . strval(I("post.rows", 100)))->where("pid=" . strval(I("post.pid")))->order("id")->select();
        $result_ary["total"] = $gclb->count();
        $result_ary["rows"]  = $list_ary;

        $this->ajaxReturn($result_ary);
    }

    public function updateJdk()
    {
        $gclb = M("Gcjdk");
        $id   = I("post.row")["id"];

        if ($id == -1)
        {
            //添加
            $gclb->field("id", true)->add(I("post.row"));
            $id = $gclb->getLastInsID();
        }
        else
        {
            //更改
            $gclb->where("id=" . strval($id))->save(I("post.row"));
        }

        $result_ary["id"] = $id;
        $this->ajaxReturn($result_ary);
    }

    public function delJdk()
    {
        $gclb = M("Gcjdk");
        $gclb->where("id=" . I("post.row")["id"])->delete();
        //$gclb->where("id=100")->delete();

        $result_ary["row"] = I("post.row");
        // $result_ary["row"] = $gclb->getLastSql();
        $this->ajaxReturn($result_ary);
    }

    public function col_dis_gc_detail()
    {
        //结构定义
        $rows    = [];
        $rows[0] = ["field" => "ht_je", "name" => "合同金额（万）", "value" => "", "editor" => [type => 'numberbox', options => ["min" => 0, "precision" => 2]], "bz" => ""];
        $rows[1] = ["field" => "kg_rq", "name" => "开工日期", "value" => "", "editor" => [type => 'datebox', options => []]];
        $rows[2] = ["field" => "fh_rq", "name" => "发货日期", "value" => "", "editor" => [type => 'datebox', options => []]];

        $rows[3] = ["field" => "kp_rq", "name" => "开票日期", "value" => "", "editor" => [type => 'datebox', options => []]];
        $rows[4] = ["field" => "kp_je", "name" => "开票金额（万）", "value" => "", "editor" => [type => 'numberbox', options => ["min" => 0, "precision" => 2]]];

        $rows[5] = ["field" => "ts_sf", "name" => "是否调试", "value" => "", "editor" => [type => 'checkbox', options => ["on" => "是", "off" => "否"]]];
        $rows[6] = ["field" => "tswc_rq", "name" => "调试完成日期", "value" => "", "editor" => [type => 'datebox', options => []]];

        $rows[7] = ["field" => "ys_sf", "name" => "是否验收", "value" => "", "editor" => [type => 'checkbox', options => ["on" => "是", "off" => "否"]]];
        $rows[8] = ["field" => "ys_rq", "name" => "验收日期", "value" => "", "editor" => [type => 'datebox', options => []]];

        $rows[9]  = ["field" => "zbqx", "name" => "质保期限", "value" => "", "editor" => [type => 'text', options => []]];
        $rows[10] = ["field" => "zbdq_rq", "name" => "质保到期日", "value" => "", "editor" => [type => 'datebox', options => []]];

        //foreach ($rows as $k => $v)
        //    unset($rows[$k]["editor"]);

        //数据填入
        $gclb = M("Gclb");
        $data = $gclb->where("id=" . strval(I("post.id")))->find();
        if ($data != NULL)
        {
            foreach ($rows as $k => $v)
            {
                $rows[$k]["value"] = $data[$rows[$k]["field"]];
            }
        }
        //备注
        $rows[0]["bz"] = $data["bz"];

        $result_ary["rows"] = $rows;
        $this->ajaxReturn($result_ary);
    }

    public function col_dis_gc_kffs()
    {
        //结构定义
        $rows = [];
        array_push($rows, ["kx" => "预付款", "fk_bl" => "", "fk_je" => ""]);
        array_push($rows, ["kx" => "提货款", "fk_bl" => "", "fk_je" => ""]);
        array_push($rows, ["kx" => "调试款", "fk_bl" => "", "fk_je" => ""]);
        array_push($rows, ["kx" => "质保金", "fk_bl" => "", "fk_je" => ""]);

        //数据填入
        $gclb = M("Gclb");
        $data = $gclb->where("id=" . strval(I("post.id")))->field("fkfs")->find();
        // $data = $gclb->where("id=29")->field("fkfs")->find();

        if ($data != NULL)
        {
            $data1_array = [];
            $t1_array    = explode(SPSTR_1, $data["fkfs"]);
            foreach ($t1_array as $k => $v)
            {
                $t2_array                  = explode(SPSTR_2, $v);
                $data1_array[$t2_array[0]] = $t2_array;
            }

            foreach ($rows as $k => $v)
            {
                $rows[$k]["fk_bl"] = $data1_array[$rows[$k]["kx"]][1];
                $rows[$k]["fk_je"] = $data1_array[$rows[$k]["kx"]][2];
            }
        }

        $this->ajaxReturn($rows);
    }

    public function saveGcDetailData()
    {
        $mdfData = D("Gclb");

        $data = I("post.data");

        //数据校验
        foreach ($data as $k => $v)
        {
            if (substr($k, -3, 3) == "_rq" && trim($v) == "")
                $data[$k] = NULL;
            if (substr($k, -3, 3) == "_sf" && trim($v) != "是")
                $data[$k] = "否";
        }
        $mdfData->where("id=" . I("post.id"))->save($data);

        $this->ajaxReturn($data);

        /*
        if (!$mdfData->validate($rules)->create($data))
        {
            $result_ary = array("error" => 1, "infoAry" => $mdfData->getError());
            $this->ajaxReturn($result_ary);
        }
        else
        {
            if ($modiFlag == 1)
            {
                $data["cr_data"] = date("Y-m-d"); //数据格式 2017-01-01
                $data["id"]      = $mdfData->field("id", true)->add($data);
            }
            if ($modiFlag == 2)

            $result_ary = array("error" => 0, "infoAry" => $data);
            $this->ajaxReturn($result_ary);
        }
         * */
    }

    public function loadNotice()
    {
        $directory              = NEWS_PATH . "/";
        $filename               = $directory . "news.txt";
        $notice                 = "";
        $notice_update_datetime = "";

        if (file_exists($filename))
        {
            //公告内容
            $fp     = fopen($filename, "r");
            $notice = fread($fp, filesize($filename));
            fclose($fp);

            //返回公告文件时间日期字符串
            $notice_update_datetime = date("Y-m-d H:i:s", filemtime($filename));
        }

        //补齐空格
        if (I("post.disFlag") == 1)
        {
            for ($i = 0; $i < 260 - mb_strlen($notice); $i++)
                $notice = $notice . "　";
        }

        $result_ary["notice"]                 = $notice;
        $result_ary["notice_update_datetime"] = $notice_update_datetime;
        $this->ajaxReturn($result_ary);
    }

    public function saveNotice()
    {
        $directory = NEWS_PATH . "/";
        $filename  = $directory . "news.txt";

        if (is_dir($directory) == false)
            mkdir($directory, 0777, true);

        $fp = fopen($filename, "w");
        fwrite($fp, I("post.notice_text"));
        fclose($fp);
    }

    public function downloadAllPic()
    {
        $fl      = I("post.fl");
        $gclb    = M("Gclb");
        $cr_data = $gclb->where("id=" . I("post.id"))->getField("cr_data");

        //遍历目录
        $ht_list = [];
        // $directory = DATA_ATT_ROOT_PATH . "/" . PIC_SUB_PATH . "/" . explode("-", $cr_data)[0] . "/" . explode("-", $cr_data)[1];
        $directory = PIC_SUB_PATH . "/" . explode("-", $cr_data)[0] . "/" . explode("-", $cr_data)[1];

        if (is_dir($directory) == true)
        {
            $mydir = dir($directory);
            while ($file = $mydir->read())
            {
                if ((is_dir($directory . "/" . $file)) AND ($file != ".") AND ($file != ".."))
                {
                }
                else if (($file != ".") AND ($file != ".."))
                {
                    if (strpos($file, I("post.id") . "_" . $fl) !== false)
                        array_push($ht_list, $directory . "/" . $file);
                }
            }
            $mydir->close();
        }

        //生成压缩包
        $directory = JSXY_PACK_PATH . "/";
        mkdir($directory, 0777, true);

        //清除半小时以上的包
        if (is_dir($directory) == true)
        {
            $cu_time = time();
            $mydir   = dir($directory);
            while ($file = $mydir->read())
            {
                if ((is_dir($directory . "/" . $file)) AND ($file != ".") AND ($file != ".."))
                {
                }
                else if (($file != ".") AND ($file != ".."))
                {
                    $delFlag = false;
                    if (APP_DELTEMPPACK_FLAG == true)
                    {
                        $delFlag = true;
                    }
                    else
                    {
                        if ($cu_time - intval(explode("_", $file)[1]) > 60 * 30)
                            $delFlag = true;
                    }

                    if ($delFlag == true)
                    {
                        if (file_exists($directory . $file))
                            unlink($directory . $file);
                    }
                }
            }
            $mydir->close();
        }

        //确定压缩包文件名
        for ($i = 1; $i < 1000; $i++)
        {
            //已时间戳加序号为文件名
            $filename = $directory . "pack" . "_" . strval(time()) . "_" . strval($i) . ".zip";
            if (file_exists($filename) == false)
                break;
        }

        //生成压缩包
        if (count($ht_list) > 0)
        {
            $zip = new \ZipArchive();
            $zip->open($filename, \ZipArchive::OVERWRITE);
            foreach ($ht_list as $k => $v)
            {
                $zip->addFile($v, basename($v));
            }
            $zip->close();
        }

        $result_ary = array("filename" => $filename, "filecount" => count($ht_list));
        $this->ajaxReturn($result_ary);
    }

    public function getListGcFile()
    {
        $gclb    = M("Gclb");
        $cr_data = $gclb->where("id=" . I("post.id"))->getField("cr_data");
        // $directory = DATA_ATT_ROOT_PATH . "/" . GCJF_SUB_PATH . "/" . explode("-", $cr_data)[0] . "/" . explode("-", $cr_data)[1] . "/";
        $directory = GCJF_SUB_PATH . "/" . explode("-", $cr_data)[0] . "/" . explode("-", $cr_data)[1] . "/";

        $temp_arr = [];
        $fileList = getFileList($directory);
        foreach ($fileList as $k => $v)
        {
            if (explode("_", $v)[0] == I("post.id"))
                $temp_arr[explode(FILE_SPSTR_1, $v)[1]] = ["file" => iconv('gbk', 'utf-8', $directory . $v), "file_spstr_1" => FILE_SPSTR_1];
        }
        // array_push($rows, ["file" => iconv('gbk', 'utf-8', $directory . $v), "file_spstr_1" => FILE_SPSTR_1]);

        //按key值排序 (key值为上传时的文件名)
        ksort($temp_arr);
        $rows = [];
        foreach ($temp_arr as $k => $v)
            array_push($rows, $v);

        $result_ary["rows"] = $rows;
        $this->ajaxReturn($result_ary);
    }
}